package com.example.java_chatroom.api;

import com.example.java_chatroom.model.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
public class AdminAPI {
    @Resource
    AdminMapper adminMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    private MessageMapper messageMapper;

    @PostMapping("/adminLogin")
    @ResponseBody
    public Object adminLogin(String adminUsername, String adminPassword, HttpServletRequest req) {
        // 1. 先去数据库中查查, 看 username 能否找到对应的 user 对象
        //    如果能找到则看一下密码是否匹配
        Admin admin = adminMapper.selectByName(adminUsername);
        if (admin == null ) {
            // 这俩条件具备一个, 就是登录失败!! 同时返回一个空的对象即可.
            System.out.println("登录失败! 用户名或者密码错误! " + admin);
            return new User();
        }

        // 2. 如果都匹配, 登录成功! 创建会话!!
        HttpSession session = req.getSession(true);
        session.setAttribute("admin", admin);
        // 在返回之前, 把 password 给干掉. 避免返回不必要的信息.
        admin.setAdminPassword("");
        return admin;
    }

    @GetMapping("/getAllUser")
    @ResponseBody
    public List<User> getAllUser(HttpServletRequest req) {
        List<User> users = new ArrayList<>();
        users = userMapper.getAllUsers();
        Collections.reverse(users);
        return users;
    }

    @PostMapping("/updateStatus")
    @ResponseBody
    public int updateStatus(@RequestParam(required = false) Integer userId, @RequestParam(required = false)Integer status) {
        return userMapper.updateStatus(userId, status);
    }

    @GetMapping("/getAllMessage")
    public Object getAllMessage() {
        List<Message> messages = messageMapper.getAllMessage();
        // 针对查询结果, 进行逆置操作. 毕竟界面上需要的是按照时间升序排列的消息. 此处得到的是降序排列的消息.
        for(Message message : messages) {
            List<User> users = userMapper.getAllUsers();
            for(User user : users) {
                if(user.getUserId() == message.getFromId()) {
                    message.setFromName(user.getUsername());
                    break;
                }
            }
        }
        Collections.reverse(messages);
        return messages;
    }

    @DeleteMapping("deleteMessage/{id}")
    @ResponseBody
    public int deleteMessage(@PathVariable("id") int id) {
        return messageMapper.deleteMessage(id);
    }

    @RequestMapping("/adminLogout")
    public boolean logout(HttpSession session){
        session.removeAttribute("admin");
        return true;
    }

}

